package com.codefish.codefishseckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codefish.codefishseckill.entity.User;
import com.codefish.codefishseckill.mapper.UserMapper;
import com.codefish.codefishseckill.service.UserService;
import com.codefish.codefishseckill.utils.CookieUtil;
import com.codefish.codefishseckill.utils.MD5PasswordUtil;
import com.codefish.codefishseckill.utils.UuidUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author codefish
 * @since 2022-07-05
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean doLogin(Long username, String password, HttpServletRequest request, HttpServletResponse response) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.select("password", "salt", "nickname", "username").eq("username", username);
        User user = this.getOne(query);

        if (user == null) {
            return false;
        }

        if (MD5PasswordUtil.verifyPassword(password, user.getPassword(), user.getSalt(), false)) {
            String token = UuidUtils.randomUUID();
            redisTemplate.opsForValue().set(UserService.USER_INFO_TOKEN_PREFIX + token, user, 7 * CookieUtil.DAY, TimeUnit.SECONDS);
            CookieUtil.setCookie(response, CookieUtil.USER_INFO_KEY, token, 7 * CookieUtil.DAY, "/");
            // request.getSession().setAttribute("nickname", user.getNickname());
            return true;
        } else {
            return false;
        }
    }

    @Override
    public User getUserByToken(String token) {

        if (StringUtils.isEmpty(token)) {
            return null;
        }
        return (User) redisTemplate.opsForValue().get(UserService.USER_INFO_TOKEN_PREFIX + token);
    }

    @Override
    public User getUserByEmail(String email) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email).select("nickname", "username","identification");
        return this.getOne(queryWrapper);
    }
}
